package com.xbongbong.saas.analytical.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.help.team.TeamUserHelp;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SupplierErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SupplierContactErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.analytical.SaasValidateAnalyticalService;
import com.xbongbong.saas.domain.entity.ext.SupplierEntityExt;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.help.SaveFormatHelp;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/07/15 17:15
 */
@Service("supplierContactAnalyticalServiceImpl")
public class SupplierContactValidateAnalyticalServiceImpl implements SaasValidateAnalyticalService {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(SupplierContactValidateAnalyticalServiceImpl.class);
    private final static int DEL_STATUS = 1;
    private final static int SUPPLIER_CONTACT_NAME_MAX = 30;
    private final static int SUPPLIER_CONTACT_POSITION_MAX = 30;

    @Resource
    private SupplierModel supplierModel;
    @Resource
    private TeamUserHelp teamUserHelp;


    @Override
    public List<Integer> type() {
        return Arrays.asList(XbbRefTypeEnum.SUPPLIER_CONTACT.getCode());
    }

    @Override
    public void analyticalData(ValidateDataDTO validateDataDTO) throws XbbException {
        beforeSave(validateDataDTO);
        teamUserHelp.beforeVerifyUserTeam(validateDataDTO);
    }
    
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        try {
            JSONObject data = validateDataDTO.getData();
            SaveFormatHelp.formatLinkBusiness4Save(data,SupplierContactEnum.SUPPLIER_ID.getAttr(),SupplierContactEnum.SUPPLIER_ID_LINK_TEXT.getAttr(), SupplierContactEnum.SUPPLIER_ID.getFieldType());
            SaveFormatHelp.formatBirthday4Save(data,SupplierContactEnum.BIRTHDAY.getAttr(),SupplierContactEnum.BIRTHDAY_FLAG.getAttr(), SupplierContactEnum.BIRTHDAY_MMDD.getAttr());
            // 参数合理化校验
            parameterCheck(validateDataDTO);
        } catch (XbbException e) {
            throw e;
        }  catch (Exception e) {
            LOGGER.error("supplierContactAnalyticalServiceImpl.beforeSave error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 供应商联系人参数保存前对相关参数进行合理化校验
     *
     * @param validateDataDTO 前端传参数据
     * @throws XbbException 参数不符合要求错误提醒
     * @author Jian.Wang
     * @date 2019/1/30 15:32
     * @since v1.0
     *
     * */
    private void parameterCheck(ValidateDataDTO validateDataDTO) throws XbbException {
        // 校验供应商是否存在或被删除
        if ( Objects.isNull(validateDataDTO.getIsNew()) || !validateDataDTO.getIsNew() ) {
            checkSupplierExists(validateDataDTO);
        }

        JSONObject data = validateDataDTO.getData();
        String supplierContactName = FastJsonHelper.getStringFromFormData(data, SupplierContactEnum.NAME.getAttr());
        String position = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierContactEnum.POSITION.getAttr(), "");

        if (StringUtil.isEmpty(supplierContactName)) {
            throw new XbbException(SupplierContactErrorCodeEnum.API_ERROR_252001);
        } else if (supplierContactName.length() > SUPPLIER_CONTACT_NAME_MAX) {
            throw new XbbException(SupplierContactErrorCodeEnum.API_ERROR_252002);
        }
        if (position.length() > SUPPLIER_CONTACT_POSITION_MAX) {
            throw new XbbException(SupplierContactErrorCodeEnum.API_ERROR_252004);
        }
        // 校验供应商联系电话是否存在或是否格式正确 25967
        //checkContactNumber(data);
    }

    /**
     * 校验供应商是否存在或被删除
     *
     * @param validateDataDTO 数据源
     * @throws XbbException 如果供应商不存在或已被删除抛出错误提示
     * @author Jian.Wang
     * @date 2019/1/31 19:10
     * @since v1.0
     **/
    private void checkSupplierExists(ValidateDataDTO validateDataDTO) throws XbbException {
        JSONObject data = validateDataDTO.getData();
        if (data.containsKey(SupplierContactEnum.SUPPLIER_ID.getAttr())) {
            long supplierId = FastJsonHelper.getLongFromFormData(data, SupplierContactEnum.SUPPLIER_ID.getAttr());
            String corpid = validateDataDTO.getCorpid();
            SupplierEntityExt supplierEntityExt = supplierModel.getByKey(supplierId, corpid);
            if (null != supplierEntityExt) {
                if (Objects.equals(supplierEntityExt.getDel(),DEL_STATUS)) {
                    throw new XbbException(SupplierErrorCodeEnum.API_ERROR_233003);
                }
            } else {
                throw new XbbException(SupplierErrorCodeEnum.API_ERROR_233003);
            }
        }
    }
}
